package com.arunsawad.ilertu.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.arunsawad.ilertu.common.DbHandler;
import com.arunsawad.ilertu.entity.Emergency;

public class EmergencyDao {
	private DbHandler dbHandler;

	public EmergencyDao(Context context) {
		dbHandler = new DbHandler(context);
	}

	public List<Emergency> getEmergencies(String searchStr, String language) {
		List<Emergency> emergencies = new ArrayList<Emergency>();
		// Select All Query
		String query = "SELECT name" + language
				+ ", website, image, tel FROM emergencies WHERE name"
				+ language + " LIKE '%" + searchStr + "%' OR tel LIKE '%"
				+ searchStr + "%'";

		SQLiteDatabase db = dbHandler.getWritableDatabase();
		Cursor cursor = db.rawQuery(query, null);

		if (cursor.moveToFirst()) {
			do {
				Emergency emergency = new Emergency();
				emergency.setName(cursor.getString(0));
				emergency.setWebsite(cursor.getString(1));
				emergency.setImageFilename(cursor.getString(2));
				emergency.setTel(cursor.getString(3));

				emergencies.add(emergency);
			} while (cursor.moveToNext());
		}

		db.close();
		return emergencies;
	}

	public void addEmergencies(List<Emergency> emergencies) {
		for (Emergency emergency : emergencies) {
			addEmergency(emergency);
		}
	}

	public void addEmergency(Emergency emergency) {
		SQLiteDatabase db = dbHandler.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put("nameEn", emergency.getNameEn());
		values.put("nameTh", emergency.getNameTh());
		values.put("website", emergency.getWebsite());
		values.put("image", emergency.getImageFilename());
		values.put("tel", emergency.getTel());

		db.insert("emergencies", null, values);
		db.close();
	}
}
